<template>
 
    <a-spin :spinning="confirmLoading" :style="{height:viewheight+'px'}">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <div id="view" style="display:flex"    >
          <div class="videodiv">
            <div class="video-container" :style="{height:imgheight-bkcswidth+'px',width:imgwith-bkcsheight+'px'}" >
            </div>
            <video ref="video" style="    position: relative;z-index: 1;" :style="{height:imgheight+'px',width:imgwith+'px'}" ></video>
            <video ref="videoy" style="display: none;  position: relative;z-index: 999;"   :style="{height:NCameraResolution.height+'px',width:NCameraResolution.width+'px'}" ></video>
          </div>
          
         
          <!-- <canvas style="display: none" id="canvasCamera"></canvas> -->
          <canvas ref="canvas" style="display: none;" :style="{height:NCameraResolution.width+'px',width:NCameraResolution.height+'px'}" id="canvasCamera"></canvas>
          <!-- <div v-if="imgSrc11" class="img_bg_camera">
            <img :src="imgSrc11" class="tx_img" />
          </div> -->
          <!-- <img id="view1" :style="{height:imgheight+'px',width:imgwith+'px'}" :src="'data:image/jpg;base64,' + Frameimg " alt="主摄像头"> -->

          <div id="container" class="down-tree"  style="overflow-y:auto; width:100%;display:flex;flex-wrap:wrap;border:1px dashed #d9d5d5;"  > 
            <div :class="'hopic'+index" v-for="(item,index) in imglist" :key="index" style="width:105px;margin:5px"   v-viewer="{movable: false}" >
             
              <img :id="'img'+index" class='pic' width='105px'  height='85px' :src="item" @contextmenu.prevent="onContextmenu"    />
            
            
            </div>
            
  
          </div>  
        </div>
        

        <div class="table-operator"> 
          <!-- <a-checkbox v-model:checked="rectifying" @change="OpenDeskew" style="margin-left: 10px;">纠偏裁边</a-checkbox> -->
          <a-select  v-model="cameravalue"  @change="handleChange" style="width: 200px;" > 
            <a-select-option v-for="(camera, index) in cameraNames"  :value="camera.deviceId">{{ camera.label }}</a-select-option> 
          </a-select>
          <a-button @click="OpenCamera()" :loading="openLoading" type="primary" icon="file-image" style="margin-left: 10px;">打开高拍仪</a-button>
          <a-button @click="close_view1()" :loading="closeLoading" icon="file-excel">关闭高拍仪</a-button>  
          <a-button @click="GrabImage()" :loading="GrabLoading" type="primary" icon="picture" :disabled="hubmit"   >拍照</a-button>  
          <a-button @click="handleOk()"  :loading="iconLoading" type="danger" icon="check-square">提交</a-button>   
        </div>
        <a-modal v-model:visible="isLoading" :footer="null" :keyboard="false" :maskClosable="false" :closable="false" 
        :width="100"
        :height="100"    wrapClassName="web">
          <div style="text-align:center;margin-top:20px;" >
            <a-spin :size="large"/>
            <p>loading...</p> 
          </div>
        </a-modal>

        <!-- PDF --> 
        <!-- 设备 --> 
        <!-- 操作日志 --> 
      </a-form-model>
   
    </a-spin>
    
</template>

<script>
  import Vue from 'vue'
  import axios from 'axios' 
  import { validateDuplicateValue } from '@/utils/util'
  import Contextmenu from "vue-contextmenujs" 
  import Viewer from 'v-viewer'
  import 'viewerjs/dist/viewer.css'
  import { mapGetters } from 'vuex' 
  Vue.use(Viewer)
  // 全局配置
  Viewer.setDefaults({
    zIndex: 9999, // 图片查看器的层级
    navbar: false, // 隐藏导航栏
    toolbar: {
      zoomIn: true,
      zoomOut: true,
      oneToOne: true,
      reset: true,
      play: true,
      rotateLeft: true, 
      rotateRight: true,
      flipHorizontal: true,
      flipVertical: true,
    },
  }) 
  Vue.use(Viewer)
  Vue.use(Contextmenu);
  export default {
    name: "Camera",
    components: {  
    },
    data () {
      return {  
        isLoading:false,
        iconLoading:false,
        openLoading:false,
        closeLoading:false,
        GrabLoading:false,
        hubmit:true,
        imgwith:350,
        imgheight:400,
        Frameimg:"", //Frame图片
        rectifying:false,//摄像头纠偏
        autocamera:false,//自动拍照
        quality:0,//图片质量
        ColorMode:0,//色彩模式
        viewheight:450,
        disabled:false,
        title:"操作",
        qualitylist:[
          {id:0,name:'默认质量'},
          {id:1,name:'高质量'},
          {id:2,name:'较高质量'},
          {id:3,name:'中等质量'},
          {id:4,name:'较差质量'},
          {id:5,name:'差质量'}, 
        ],
        ColorModeList:[
          {id:0,name:'彩色模式'},
          {id:1,name:'灰色模式'},
          {id:2,name:'黑白模式'},
          {id:3,name:'白纸印章'},
          {id:4,name:'去除背景'}, 
        ],
        width:800,
        rotatv:0,
        modelvisible: false,
        visible: true,
        model:{
         },
        labelCol: {
          xs: { span: 4 },
          sm: { span: 9 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 },
        },
        twolabelCol: {
          xs: { span: 4 },
          sm: { span: 5 },
        },
        twowrapperCol: {
          xs: { span: 24 },
          sm: { span: 19 },
        }, 
        confirmLoading: false,
        validatorRules: {
        },
        url: {
          add: "/ml/daMl/add",
          edit: "/ml/daMl/edit",
        },
        expandedRowKeys:[],
        pidField:"pid",
        imglist:[],
        timer: "",
        cameraCount: 0,
        cameraNames: [],
        cameraResolutions:null,
        NCameraResolution:{width:0,height:0},
        cameravalue:"",
        bkcswidth:100,
        bkcsheight:100,
      }
    },
    created () {
       //备份model原始值  
       this.modelDefault = JSON.parse(JSON.stringify(this.model));
       console.log("打开高拍仪");
        let timer = setTimeout(() => { 
          
          
          this.getCameraNumber();
          
        }, 1000)
       
    },
    methods: {
      ...mapGetters(["lebcamera"]),  
      show(){
        this.iconLoading=false;
        this.openLoading=false;
        this.closeLoading=false;
        this.GrabLoading=false;
        // this.hubmit=true;
        this.imglist = [];
        // console.log("打开高拍仪");
        // let timer = setTimeout(() => {
        //   this.close_view1();
          
        //   this.OpenCamera();
        // }, 3000)

      }, 
      handleChange(value){
          console.log("select change", value )
          this.getCameraResolution(value);
          this.OpenCamera(value);
      },
      async  getCameraNumber(){
          if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
            console.log('enumerateDevices is not supported');
            return;
          }
    
          try {
            const devices =  await  navigator.mediaDevices.enumerateDevices();
            console.log("devices", devices)
            devices.forEach(device => {
              if (device.kind === 'videoinput') {
                let data  = {deviceId:device.deviceId,label:device.label}
                this.cameraNames.push(data);
              }
            });
            this.cameraCount = this.cameraNames.length;
            console.log('Camera count:', this.cameraCount);
            console.log('Camera names:', this.cameraNames);
            console.log("获取摄像头信息", this.cameraNames )   
            console.log("摄像头deviceId",this.cameraNames[0].deviceId) 
            this.cameravalue = this.cameraNames[0].deviceId;
            this.getCameraResolution(this.cameraNames[0].deviceId)
            this.OpenCamera(this.cameraNames[0].deviceId);
          } catch (err) {
            console.error('Error getting devices:', err);
          }
        
      }, 
      async getCameraResolution(deviceId) {
        try {
          const stream = await navigator.mediaDevices.getUserMedia({  video:  {
                      deviceId: { exact: deviceId }
                    } });
          const track = stream.getVideoTracks()[0];
          const capabilities = track.getCapabilities();
          this.cameraResolutions = {
            max: `${capabilities.maxWidth}x${capabilities.maxHeight}`,
            min: `${capabilities.minWidth}x${capabilities.minHeight}`
          };
          stream.getTracks().forEach(track => track.stop());
          this.NCameraResolution.width = capabilities.width.max;
          this.NCameraResolution.height = capabilities.height.max;
          let js = this.imgheight/this.NCameraResolution.height;
          this.imgwith = Math.floor(this.NCameraResolution.width*js); 
          console.log("分辨率",capabilities.width.max,capabilities.height.max )
        } catch (error) {
          console.error('获取摄像头分辨率失败:', error);
        }
      },
      getUrlBase64(url, ext, callback) {
          var canvas = document.createElement("canvas");   //创建canvas DOM元素
          var ctx = canvas.getContext("2d");
          var img = new Image;
          img.crossOrigin = 'Anonymous';
          img.src = "data:image/jpg;base64,"+url;
          img.onload = function () { 
              // if(img.width>img.height){
              //   canvas.width = img.height-100;
              //   canvas.height = img.width-100;
              //   ctx.rotate((90 * Math.PI) / 180);
              //   ctx.drawImage(img, 40, -img.height-100, img.width-100, img.height-100); 
              // }else{
                // canvas.height = img.height-100; //指定画板的高度,自定义
                // canvas.width = img.width-100; //指定画板的宽度，自定义 
                // ctx.drawImage(img, -40, -40, img.width-40, img.height-40); //参数可自定义

                canvas.height = img.height; //指定画板的高度,自定义
                canvas.width = img.width; //指定画板的宽度，自定义 
                ctx.drawImage(img, 0, 0, img.width, img.height); //参数可自定义
              // }
              var dataURL = canvas.toDataURL("image/" + ext);
              callback.call(this, dataURL); //回掉函数获取Base64编码
              canvas = null;
          };
         
      },
      onContextmenu(event) { 
        let id = event.srcElement.attributes[0].value;

        this.$contextmenu({
            items: [
              {
                label: "预览(B)",
                onClick: () => { 
                  console.log("返回(B)"); 

                  const viewer = this.$el.querySelector('.hopic'+id.replace("img","")).$viewer
                  viewer.show()
                }
              },
              { 
                label: "删除(F)",
                onClick: () => { 
                  console.log("返回(B)");
                  this.imglist.splice(id.replace("img",""),1);
                }
              },   
            ],
            event,
            //x: event.clientX,
            //y: event.clientY,
            customClass: "class-a",
            zIndex: 9999,
            minWidth: 230
          });
          return false; 
      },

      deleteimg(index){
        this.imglist.splice(index,1);
      },
      start(){
        this.timer = setInterval(this.getFarme, 2000); // 注意: 第一个参数为方法名的时候不要加括号;
      },
      getRotate(){
        axios.get(window._CONFIG['LinuxGPYUrl']+"/getRotate", '').then((res)=>{
            if (res.data.returnCode == 0){
                console.log("返回角度",res);
               switch(res.data.data){
                    case 0: this.imgwith = 600; this.imgheight = 400; break;
                    case 1: this.imgwith = 350; this.imgheight = 400; break;
                    case 2: this.imgwith = 600; this.imgheight = 400; break; 
                    case 3: this.imgwith = 350; this.imgheight = 400; break; 
               }
            }
        }) 
      },
      getFarme(){
        axios.get(window._CONFIG['LinuxGPYUrl']+"/getFrame", '').then((res)=>{
            if (res.data.returnCode == 0){
               this.Frameimg = res.data.data.img;
            }
        }) 
      },
      OpenDeskew(){ 
        if (this.rectifying == false) { 
            this.OpenCorrect("0");
        } else { 
            this.OpenCorrect("1");
        }
      },     
      handleOk(){         
        if (this.imglist.length == 0){
          this.$message.error("请先拍照");
          return
        } 
        this.iconLoading = true;
        // this.hubmit = true;
        console.log("提交");
        this.$emit('ok','carmera',this.imglist) 
      },
      OpenCorrect(lx){ 
        axios.get(window._CONFIG['LinuxGPYUrl']+"/EnableDeskImage?enable="+lx, '').then((res)=>{
           if (res.data.returnCode != 0){
            this.$message.error(res.data.returnMsg)
           }
        })
      }, 
      // 打开主头视频
      OpenCamera(deviceId){
        this.openLoading = true;
        this.isLoading = true;

        // 获取 canvas 画布
        this.canvas = document.getElementById("canvasCamera");
        this.context = this.canvas.getContext("2d");
        // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        console.log("Cindex", deviceId );
        // 正常支持版本
        navigator.mediaDevices
          .getUserMedia({
            video:  {
                      deviceId: { exact: deviceId },
                      // width: this.NCameraResolution.width,
                      // height: this.NCameraResolution.height
                    }
          })
          .then((stream) => {
            // 摄像头开启成功
            this.mediaStreamTrack =
            typeof stream.stop === "function" ? stream : stream.getTracks()[0];

 
            this.video_stream = stream;
            this.$refs.video.srcObject = stream;
            this.$refs.video.play();

            this.$refs.videoy.srcObject = stream;
            this.$refs.videoy.play();
            this.openLoading = false;
            this.isLoading = false;
            this.hubmit = false;
          })
          .catch((err) => {
            console.log(err);
            this.openLoading = false; 
            this.isLoading = false; 
          });    
      },
      // 关闭主头视频
      close_view1(){  
        this.closeLoading = true;
        axios.get(window._CONFIG['LinuxGPYUrl']+"/StopPreview?dev_idx=0", '').then((res)=>{
           this.closeLoading = false;
           if (res.data.returnCode == 0){
              console.log("关闭主头视频")
              clearInterval(this.timer);
              this.hubmit = true;
           }
        }) 
      },

      rotate(){
        
      },     
      close () {
        this.$emit('close');
        this.visible = false;
        this.$refs.form.clearValidate()
      }, 
      handleCancel () {
        this.close()
      },
      submitSuccess(formData,flag){
        if(!formData.id){
          let treeData = this.$refs.treeSelect.getCurrTreeData()
          this.expandedRowKeys=[]
          this.getExpandKeysByPid(formData[this.pidField],treeData,treeData)
          this.$emit('ok',formData,this.expandedRowKeys.reverse());
        }else{
          this.$emit('ok',formData,flag);
        }
      },
      getExpandKeysByPid(pid,arr,all){
        if(pid && arr && arr.length>0){
          for(let i=0;i<arr.length;i++){
            if(arr[i].key==pid){
              this.expandedRowKeys.push(arr[i].key)
              this.getExpandKeysByPid(arr[i]['parentId'],all,all)
            }else{
              this.getExpandKeysByPid(pid,arr[i].children,all)
            }
          }
        }
      }, 
      GrabImage(){ 
        let that = this;
        that.isLoading = true;
        that.GrabLoading = true;
        console.log("拍照");


        const video = this.$refs.videoy;
        console.log(video);
        const canvas = this.$refs.canvas;
        const context = canvas.getContext('2d'); 
        
        canvas.height = this.NCameraResolution.height;//Math.floor( (this.NCameraResolution.height* (this.imgheight - this.bkcsheight) )/ this.imgheight);

        canvas.width = this.NCameraResolution.width;//Math.floor(this.NCameraResolution.width * (canvas.height/this.NCameraResolution.height));


        let widthxs =  Math.floor((this.bkcswidth*this.NCameraResolution.width)/this.imgwith);
        let hegihtxs =  Math.floor((this.bkcsheight*this.NCameraResolution.height)/this.imgheight);
        console.log(canvas.width,canvas.height)
        console.log(widthxs,hegihtxs)
        console.log(video.width,video.height )
        context.drawImage(video,0,  0,canvas.width, canvas.height);
        // context.drawImage(video, widthxs,  hegihtxs, 100, 100,0,0,100,100);
        let photoSrc = canvas.toDataURL('image/png'); 

        console.log(photoSrc); 
        that.imglist.push(photoSrc)   
        // 获取设置了滚动属性的div标签
        const div = document.getElementById('container');
        // 设置滚动的顶点坐标为滚动的总高度
        div.scrollTop = div.scrollHeight + 50; 
        that.GrabLoading = false;
        that.isLoading = false; 


        
      }
      
    }
  }


  // 传递图片base64，缩略图框生成图片用来显示,并添加到PDF队列
  function add_img(img_base64){
    let img = document.createElement('img');
    img.id = 'hu' + String(Math.random());
    img.src = "data:image/jpg;base64," + img_base64;
    img.oncontextmenu = showOperation;
    img.style.width = '80px';
    img.style.height = '80px';
    document.getElementById('my_thumbnail').appendChild(img)
  }
</script>
<style>
/* 全局 */
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 10px;
}
/* 视频预览 */
#view1, #view2{
  width: 300px; 
  height: 212px;  
  border: 1px solid rgba(185, 181, 181, 0.404);
  margin-right: 5px;
}
/* 缩略图 */
#suoluetu{
  width: 100%; 
  border: 1px solid rgba(185, 181, 181, 0.404);
}
#suoluetu img{
  margin-right: 10px;
}
/* 操作按钮 */
#myactive{
  border: 1px solid yellowgreen;
  margin-top: 10px;
  padding: 10px 5px;
}
/* 操作日志 */
#mylog{
  border: 1px solid black;
  padding: 10px;
  margin-top: 10px;
  overflow: auto;
}
.ant-spin-container{
  height: 100%;
}
.ant-form ant-form-horizontal{
  height: 100%;
}
.table-operator{
  margin-top: 10px;
  text-align: right; 
} 
.video-container {
  position: relative;
}
 
#video {
  display: block;
  margin: 0 auto;
}
.video-container{
  position: absolute;
    z-index: 2;
    border: 2px solid red;
}
.videodiv{
  justify-content: center;
  align-items: center;
  display: flex;

}
/* .video-container::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0; 
  border: 2px solid red;  
  pointer-events: none; 
  position: absolute; 
  z-index: 999; 
} */
/* .hopic{
  .delete-img { 
  }
  &:hover {
    .delete-img {
      display: block;
      position: absolute;
      width: 105px;
      height: 85px;
      line-height: 85px;
      margin-top:-85px;
      background: rgba(59, 60, 61, 0.5);  
      cursor: pointer;
      text-align: center;
      i {
        
        display: block;
        font-size: 24px;
        color: white;
      }
    }
  }
} */
</style>